<template>
  <div class="historicalVersion">
    <div class="head-container">
      <div class="search-input">
        <el-input v-model="searchValue" placeholder="搜索" size="mini" clearable />
      </div>
      <div class="tree-total-container">
        <div class="left-total">
          <span class="text">版本总数</span>
          <span class="tree-node-total">{{ versionScreenData.length }}</span>
        </div>
        <div class="tree-button-group">
          <el-tooltip class="item" effect="dark" content="刷新版本列表" placement="top">
            <el-button class="tree-refresh" type="text" @click="init()">
              <svg-icon icon-class="shuaxin" />
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="version-list">
      <ul v-loading="dataLoading">
        <li v-for="(version, index) in versionScreenData" :key="'version' + index"
          :class="{ 'active': store.versionId === version.id }" @click="rowClick(version)">
          <div class="history_remark">
            <span class="version">V{{ version.version }}</span>
            <div class="button-group">
              <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
                <el-button size="small" @click.stop="updateVersionDialog(version)">
                  <svg-icon icon-class="xiugai-copy" />
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="查看关联实验" placement="bottom">
                <el-button size="small" @click.stop="correlationExperimentDialog(version)">
                  <svg-icon icon-class="guanliansousuo" />
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="还原至此版本" placement="bottom">
                <el-button size="small" @click.stop="reductionVersion(version)">
                  <svg-icon icon-class="shanchuhuanyuan" />
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除此版本" placement="bottom">
                <el-button size="small" @click.stop="deleteVersion(version)">
                  <svg-icon icon-class="icon" />
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <div v-if="version.description" class="history_desc">
            <el-tooltip class="item" effect="dark" :content="version.description" placement="right">
              <span>描述：{{ version.description }}</span>
            </el-tooltip>
          </div>
          <div class="history_info">
            <span class="user">创建者：{{ version.create_by }}</span><br>
            <span class="time">日期：{{ version.create_time }}</span>
          </div>
        </li>
      </ul>
      <div v-if="!dataLoading && versionScreenData.length === 0" class="not-version-data">
        <el-empty description="暂无数据" />
      </div>
    </div>
    <correlation-experiment v-if="correlationExperimentDialogVisible" ref="correlationExperimentDialogVisibleRef"
      v-model.visible="correlationExperimentDialogVisible" @successFun="init()" @closeFun="closeDialogExperment()" />
    <update-version-dialog-tool v-if="updateVersionDialogVisible" ref="updateVersionDialogRef"
      v-model.visible="updateVersionDialogVisible" @successFun="init()" @closeFun="closeDialog()" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from "vue";
import { designerStore } from 'src/stores/designerTool/designerTool'
import { getVersion, deleteWorkflows, putRecoveries,getWorkflowsDetail } from 'src/api/designerTool'
import correlationExperiment from './RightProperty/correlationExperimentDialog.vue'
import UpdateVersionDialogTool from './RightProperty/updateVersionDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const store = designerStore()
const props = defineProps({
  currentTab: {
    type: String,
    default: ''
  }
})
const dataLoading = ref(false)
const versionData = ref(<any>[])
const searchValue = ref('')
const correlationExperimentDialogVisible = ref(false)
const correlationExperimentDialogVisibleRef = ref(null)
const updateVersionDialogVisible = ref(false)
const updateVersionDialogRef = ref(null)
const versionScreenData = computed(() => {
  return versionData.value.filter((item: any) => {
    return searchValue.value ? (('V' + item.version).indexOf(searchValue.value) !== -1 || item.description.indexOf(searchValue.value) !== -1) : true
  })
})
watch(() => store.events.updateWorkflowVersionData.index, (newdata, oldData) => {
  if (props.currentTab === 'version') {
    init()
  }
})
watch(() => store.events.historicalVersionHandle.index, (newdata, oldData) => {
  if (props.currentTab === 'version') {
    historicalVersionHandle(store.events.historicalVersionHandle.data)
  }
})
onMounted(() => {
  init()
})
function init() {
  // if (!dataLoading.value && store.workflowInfo.template_id) {
    dataLoading.value = true
    getVersion(store.project_id, store.template_id).then((res: any) => {
      versionData.value = res.data.results
    }, (res: any) => {
      ElMessage(res.result)
    }).finally(() => {
      dataLoading.value = false
    })
  // }
}
function reductionVersion(row: any) {
  ElMessageBox.confirm(`确认要将工作流数据还原至 V${row.version} 版本吗?`, '还原版本数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    putRecoveries(store.project_id, store.workflow_id, { workflow_id: row.id }).then((res: any) => {
      ElMessage.success('还原版本成功')
      if (store.versionId) {
        store.SET_VERSION_ID('')
      } else {
        store.SET_PUBLISH_EVENT({
          key: 'resetEvent',
          data: 'init'
        })
      }
    })
  })
}
function deleteVersion(row: any) {
  ElMessageBox.confirm(`确定要删除工作流版本为 V${row.version} 的数据吗?`, '删除工作流版本', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    deleteWorkflows(store.project_id, row.id).then((res: any) => {
      ElMessage.success('删除版本成功')
      init()
      if (store.versionId && row.id === store.versionId) {
        store.SET_VERSION_ID(null)
      }
    }).catch((error) => {
      console.log(error)
    })
  })
}
function rowClick(version: any) {
  store.SET_VERSION_ID(version.id)
  getWorkflowsDetail(store.project_id,version.id).then(res=>{
    console.log(res)
  }).catch(error=>{
    console.log(error)
  })
}
function correlationExperimentDialog(row: any) {
  correlationExperimentDialogVisible.value = true
  nextTick(() => {
    (correlationExperimentDialogVisibleRef.value as any).init(row)
  })
}
function historicalVersionHandle(type: any) {
  if (store.versionId) {
    const versionIndex = versionData.value.findIndex((row: any) => row.id === store.versionId)
    if (versionIndex !== -1) {
      const rowData = versionData.value[versionIndex]
      switch (type) {
        case 'updateVersion':
          updateVersionDialog(rowData)
          break
        case 'correlation':
          correlationExperimentDialog(rowData)
          break
        case 'reduction':
          reductionVersion(rowData)
          break
        case 'delete':
          deleteVersion(rowData)
          break
        default:
      }
    }
  }
}
function updateVersionDialog(row: any) {
  updateVersionDialogVisible.value = true
  nextTick(() => {
    (updateVersionDialogRef.value as any).init(row)
  })
}
function closeDialog() {
  updateVersionDialogVisible.value = false
}
function closeDialogExperment() {
  correlationExperimentDialogVisible.value = false
}

</script>

<style lang="scss" scoped>
@import "src/css/designerStyles/index.scss";
.historicalVersion {
  height: 100%;

  .head-container {
    ::v-deep.search-input {
      display: flex;
      align-items: center;
      height: 36px;
      padding: 2px 10px;
      border-bottom: 1px solid #dcdee2;

      .el-input__inner {
        border: 0;
        padding-left: 0;
      }

      .el-input__suffix {
        right: 0;
      }
    }

    .tree-total-container {
      height: 33px;
      display: flex;
      align-items: center;
      padding: 0 10px;
      justify-content: space-between;
      border-bottom: 1px solid #dcdee2;

      .left-total {
        .text {
          color: #606266;
        }

        .tree-node-total {
          margin-left: 6px;
        }
      }

      .tree-refresh {
        color: #606266;
        font-size: 17px;
        padding: 0;
      }
    }

    .tree-node-total {
      background: #E9E9EB;
      color: #4F4F4F;
      font-size: 12px;
      border-radius: 50%;
      min-width: 20px;
      height: 20px;
      text-align: center;
      line-height: 20px;
      padding-right: 1px;
      display: inline-block;
    }
  }

  .version-list {
    height: calc(100% - 69px);
    overflow: auto;
    position: relative;

    .not-version-data {
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      height: 100%;

      li {
        display: flex;
        flex-direction: column;
        list-style: none;
        padding: 9px 16px;
        cursor: pointer;
        position: relative;
        border-bottom: 1px solid #f8f8f8;

        &:hover,
        &.active {
          background: #fafafa;

          .history_remark {
            .button-group {
              display: block;
            }

            .version {
              font-weight: bold;
            }
          }
        }

        .history_remark {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 22px;

          .version {
            color: #666;
            font-size: 14px;
          }

          .button-group {
            display: none;

            .el-button {
              border: none;
              padding: 4px;
              background: unset;

              .svg-icon {
                width: 1.2em;
                height: 1.2em;
              }
            }
          }
        }

        .history_desc {
          margin-top: 6px;

          span {
            max-width: 100%;
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            word-break: keep-all;
          }
        }

        .history_info {
          margin-top: 8px;
          color: #999;
          font-size: 13px;

          .user {}

        }
      }
    }
  }
}
</style>
